package com.qyhl.school.school.home.search;

import android.annotation.SuppressLint;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.orhanobut.hawk.Hawk;
import com.qyhl.school.R;
import com.qyhl.school.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.school.SchoolListBean;
import com.qyhl.webtv.commonlib.entity.school.SchoolReporterActBean;
import com.qyhl.webtv.commonlib.entity.school.SchoolSearchBean;
import com.qyhl.webtv.commonlib.entity.school.SchoolVlogBean;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;


import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;

@Route(path=ARouterPathConstant.SCHOOL_SHOOT)
public class SchoolSearchActivity extends BaseActivity implements SchoolSearchContract.SchoolSearchView {
    @BindView(R2.id.search_txt)
    EditText searchTxt;
    @BindView(R2.id.delete_btn)
    ImageButton deleteBtn;
    @BindView(R2.id.history_flowLayout)
    TagFlowLayout historyFlowLayout;
    @BindView(R2.id.history_layout)
    RelativeLayout historyLayout;
    @BindView(R2.id.school_tag)
    TextView schoolTag;
    @BindView(R2.id.school_recycler)
    RecyclerView schoolRecycler;
    @BindView(R2.id.vlog_tag)
    TextView vlogTag;
    @BindView(R2.id.vlog_recycler)
    RecyclerView vlogRecycler;
    @BindView(R2.id.reporter_tag)
    TextView reporterTag;
    @BindView(R2.id.report_recycler)
    RecyclerView reportRecycler;
    @BindView(R2.id.title_layout)
    LinearLayout titleLayout;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.content_layout)
    LoadingLayout contentLayout;

    private SchoolSearchPresenter mPresenter;

    private List<String> keyHistory = new ArrayList<>();//历史记录

    private String mKeyWord;

    private CommonAdapter<SchoolListBean> schoolCommonAdapter;
    private List<SchoolListBean> schoolList = new ArrayList<>();

    private List<SchoolVlogBean> vlogList = new ArrayList<>();
    private CommonAdapter<SchoolVlogBean> vlogCommonAdapter;

    private List<SchoolReporterActBean> reportList = new ArrayList<>();
    private CommonAdapter<SchoolReporterActBean> reportCommonAdapter;


    @Override
    protected int getContentView() {
        return R.layout.activity_school_search;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar.titleBar(titleLayout).statusBarDarkFont(false).init();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        contentLayout.setStatus(LoadingLayout.Success);

        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setEnableLoadMore(false);

        mPresenter = new SchoolSearchPresenter(this);

        setHistory(true);

        schoolRecycler.setLayoutManager(new LinearLayoutManager(this));

        schoolRecycler.setAdapter(schoolCommonAdapter = new CommonAdapter<SchoolListBean>(this, R.layout.item_school_column_list, schoolList) {
            @Override
            protected void convert(ViewHolder holder, SchoolListBean schoolListBean, int position) {
                holder.setText(R.id.title, schoolListBean.getName());
                holder.setText(R.id.summary, schoolListBean.getMotto());

                RoundedImageView cover = holder.getView(R.id.cover);
                Glide.with(SchoolSearchActivity.this)
                        .load(schoolListBean.getLogo())
                        .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                        .into(cover);
            }
        });

        vlogRecycler.setLayoutManager(new GridLayoutManager(this, 2));
        vlogRecycler.setAdapter(vlogCommonAdapter = new CommonAdapter<SchoolVlogBean>(this, R.layout.item_school_vlog_home, vlogList) {
            @Override
            protected void convert(ViewHolder holder, SchoolVlogBean schoolVlogBean, int position) {
                holder.setText(R.id.nickName, schoolVlogBean.getAuthor().getNickName());
                if (schoolVlogBean.getTag() != null) {
                    holder.setText(R.id.tagName, "#" + schoolVlogBean.getTag().getName() + "#");
                }
                holder.setText(R.id.description, schoolVlogBean.getInfo());

                RoundedImageView cover = holder.getView(R.id.cover);
                RoundedImageView headCover = holder.getView(R.id.head_cover);

                Glide.with(SchoolSearchActivity.this)
                        .load(schoolVlogBean.getLogo())
                        .apply(new RequestOptions().placeholder(R.drawable.cover_large_default).error(R.drawable.cover_large_default))
                        .into(cover);

                Glide.with(SchoolSearchActivity.this)
                        .load(schoolVlogBean.getAuthor().getLogo())
                        .apply(new RequestOptions().placeholder(R.drawable.comment_head_default).error(R.drawable.comment_head_default))
                        .into(headCover);
            }
        });

        reportRecycler.setLayoutManager(new LinearLayoutManager(this));
        reportRecycler.setAdapter(reportCommonAdapter = new CommonAdapter<SchoolReporterActBean>(this, R.layout.item_school_reporter_act_home, reportList) {
            @Override
            protected void convert(ViewHolder holder, SchoolReporterActBean bean, int i) {
                RoundedImageView cover = holder.getView(R.id.cover);
                Glide.with(SchoolSearchActivity.this)
                        .load(bean.getLogo())
                        .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                        .into(cover);

                holder.setText(R.id.title, bean.getTitle());

                holder.setText(R.id.address, bean.getAddress());

                holder.setVisible(R.id.sign_btn, false);

                holder.setText(R.id.num, bean.getReportCount() + "个小伙伴");

                if (bean.isReportOver()) {
                    holder.setImageResource(R.id.tag,R.drawable.school_new_home_reporter_end_tag);
                } else if(bean.isReportNotStart()){
                    holder.setImageResource(R.id.tag,R.drawable.school_new_home_reporter_forecast_tag);
                }else{
                    holder.setImageResource(R.id.tag,R.drawable.school_new_home_reporter_tag);
                }

                if (StringUtils.isNotEmpty(bean.getEndDate())) {
                    holder.setText(R.id.date, bean.getStartDate() + "—" + bean.getEndDate());
                } else {
                    holder.setText(R.id.date, bean.getStartDate());
                }
            }
        });


    }

    private void setHistory(boolean isFirst) {
        List<String> stringList = Hawk.get("school_history");
        if (stringList != null && stringList.size() > 0) {
            if (isFirst) {
                historyLayout.setVisibility(View.VISIBLE);
            }
            keyHistory.addAll(stringList);

            historyFlowLayout.setAdapter(new TagAdapter<String>(keyHistory) {
                @SuppressLint("SetTextI18n")
                @Override
                public View getView(FlowLayout parent, int position, String str) {
                    TextView tv = (TextView) LayoutInflater.from(SchoolSearchActivity.this).inflate(R.layout.item_school_histroy,
                            historyFlowLayout, false);
                    tv.setText(str);
                    return tv;
                }
            });
        } else {
            if (isFirst) {
                historyLayout.setVisibility(View.GONE);
            }
        }
    }

    @Override
    protected void setListener() {
        contentLayout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                contentLayout.setReloadButtonText("加载中...");
                mPresenter.doSearch(mKeyWord);
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.doSearch(mKeyWord);
            }
        });

        searchTxt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    historyLayout.setVisibility(View.GONE);
                    contentLayout.setVisibility(View.VISIBLE);
                    if (StringUtils.isEmpty(mKeyWord)) {
                        Toasty.normal(SchoolSearchActivity.this, "关键字不能为空！", Toast.LENGTH_SHORT).show();
                    } else {
                        showLoading();
                        mPresenter.doSearch(mKeyWord);
                        hideKeyboard(v.getWindowToken());
                    }
                }
                return false;
            }
        });

        searchTxt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                mKeyWord = editable.toString();
            }
        });

        historyFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                showLoading();
                mKeyWord = keyHistory.get(position);
                searchTxt.setText(mKeyWord);
                searchTxt.setSelection(searchTxt.length());
                mPresenter.doSearch(mKeyWord);
                return false;
            }
        });

        schoolCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                ARouter.getInstance()
                        .build(ARouterPathConstant.SCHOOL_COLUMN_DETAIL)
                        .withInt("schoolId",schoolList.get(position).getId())
                        .navigation();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        reportCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                ARouter.getInstance()
                        .build(ARouterPathConstant.SCHOOL_REPORTER_ACT_DETAIL)
                        .withInt("actId", reportList.get(position).getId())
                        .navigation();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        vlogCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", (Serializable) vlogList);

                ARouter.getInstance()
                        .build(ARouterPathConstant.SCHOOL_VLOG_PLAY)
                        .withInt("position", position)
                        .withBundle("list",bundle)
                        .navigation();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    @Override
    public void setData(SchoolSearchBean bean) {
        contentLayout.setVisibility(View.VISIBLE);
        historyLayout.setVisibility(View.GONE);
        contentLayout.setStatus(LoadingLayout.Success);
        contentLayout.setReloadButtonText("点击重试！");
        refresh.finishRefresh();
        dismissLoading();

        boolean isNew = true;
        if (Hawk.contains("school_history")) {
            List<String> historyList = Hawk.get("school_history");
            for (int i = 0; i < historyList.size(); i++) {
                if (historyList.get(i).equals(mKeyWord)) {
                    isNew = false;
                }
            }
            if (isNew) {
                historyList.add(0, mKeyWord);
                if (historyList.size() > 10) {
                    List<String> list = historyList.subList(0, 10);
                    Hawk.put("school_history", list);
                } else {
                    Hawk.put("school_history", historyList);
                }
                setHistory(false);
            }
        } else {
            List<String> historyList = new ArrayList<>();
            historyList.add(mKeyWord);
            Hawk.put("school_history", historyList);
        }

        if (bean.getSchoolList() != null && bean.getSchoolList().size() > 0) {
            schoolTag.setVisibility(View.VISIBLE);
            schoolRecycler.setVisibility(View.VISIBLE);

            schoolList.clear();
            schoolList.addAll(bean.getSchoolList());
            schoolCommonAdapter.notifyDataSetChanged();

        } else {
            schoolTag.setVisibility(View.GONE);
            schoolRecycler.setVisibility(View.GONE);
        }

        if (bean.getVlogList() != null && bean.getVlogList().size() > 0) {
            vlogTag.setVisibility(View.VISIBLE);
            vlogRecycler.setVisibility(View.VISIBLE);

            vlogList.clear();
            vlogList.addAll(bean.getVlogList());
            vlogCommonAdapter.notifyDataSetChanged();

        } else {
            vlogTag.setVisibility(View.GONE);
            vlogRecycler.setVisibility(View.GONE);
        }

        if (bean.getReportActivityList() != null && bean.getReportActivityList().size() > 0) {
            reporterTag.setVisibility(View.VISIBLE);
            reportRecycler.setVisibility(View.VISIBLE);

            reportList.clear();
            reportList.addAll(bean.getReportActivityList());
            reportCommonAdapter.notifyDataSetChanged();
        } else {
            reporterTag.setVisibility(View.GONE);
            reportRecycler.setVisibility(View.GONE);
        }

    }

    @Override
    public void setError(String msg) {
        refresh.finishRefresh();
        contentLayout.setReloadButtonText("点击重试~");
        dismissLoading();
        showToast(msg);
    }

    @OnClick({R2.id.back_btn, R2.id.search_btn, R2.id.delete_btn})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.back_btn) {
            finish();
        } else if (id == R.id.search_btn) {
            historyLayout.setVisibility(View.GONE);
            contentLayout.setVisibility(View.VISIBLE);
            if (StringUtils.isEmpty(mKeyWord)) {
                Toasty.normal(SchoolSearchActivity.this, "关键字不能为空！", Toast.LENGTH_SHORT).show();
            } else {
                showLoading();
                mPresenter.doSearch(mKeyWord);
                hideKeyboard(view.getWindowToken());
            }
        } else if (id == R.id.delete_btn) {
            Hawk.delete("school_history");
            setHistory(false);
        }
    }
}
